package com.comtime.usercenter;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.comtime.smartbox.BaseActivity;
import com.comtime.smartkilimanjaro.R;
import com.comtime.utils.MD5Util;
import com.comtime.utils.MyConfig;
import com.comtime.utils.MySharedPreferences;
import com.comtime.utils.Util;
import com.comtime.view.MyDialog;
import com.comtime.view.MyProgressDialog;
import com.comyou.comyouhttp.ComyouHttpCallBack;
import com.comyou.comyouhttp.ComyouHttpClient;
import com.comyou.comyouhttp.ComyouHttpProgram;

public class ChangePasswordActivity extends BaseActivity implements
		OnClickListener {
	EditText edt_code, edt_pwd, edt_pwd_two;
	Button btn_next, btn_sure;
	TextView tv_phone, tv_get_code, tv_one_result, tv_two_result;

	ImageView image_show_pwd, image_show_two_pwd;
	ImageView image_clear_pwd, image_clear_two_pwd;
	LinearLayout line_one, line_two, line_get_code;
	MySharedPreferences mySharedPreferences;
	int xml_choice = 1;// 第几个xml

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_changepwd);
		mySharedPreferences = MySharedPreferences.getInstance(this);
		phoneNum = mySharedPreferences.getPhoneNum();
		init();
	}

	void init() {
		// xml one
		line_one = (LinearLayout) findViewById(R.id.line_one);

		tv_phone = (TextView) findViewById(R.id.tv_phone);
		edt_code = (EditText) findViewById(R.id.et_auth_code);

		tv_get_code = (TextView) findViewById(R.id.tv_auth_code);
		tv_one_result = (TextView) findViewById(R.id.tv_one_result);

		line_get_code = (LinearLayout) findViewById(R.id.line_get_code);
		btn_next = (Button) findViewById(R.id.bt_next);

		tv_phone.setText(phoneNum.subSequence(0, 3) + "****"
				+ phoneNum.substring(7));

		line_get_code.setOnClickListener(this);
		btn_next.setOnClickListener(this);

		// xml two
		line_two = (LinearLayout) findViewById(R.id.line_two);
		image_show_pwd = (ImageView) findViewById(R.id.image_pwd_show);
		image_show_two_pwd = (ImageView) findViewById(R.id.image_again_pwd_show);

		image_show_pwd.setOnClickListener(this);
		image_show_two_pwd.setOnClickListener(this);

		image_clear_pwd = (ImageView) findViewById(R.id.image_pwd_delete);
		image_clear_two_pwd = (ImageView) findViewById(R.id.image_again_pwd_delete);

		image_clear_pwd.setOnClickListener(this);
		image_clear_two_pwd.setOnClickListener(this);

		edt_pwd = (EditText) findViewById(R.id.et_pwd);
		edt_pwd_two = (EditText) findViewById(R.id.et_again_pwd);

		tv_two_result = (TextView) findViewById(R.id.tv_two_result);
		btn_sure = (Button) findViewById(R.id.bt_sure);
		btn_sure.setOnClickListener(this);

		handler.post(clearRunnable);
	}

	/**
	 * 返回键
	 * 
	 * @param v
	 */
	public void BackAction(View v) {
		this.finish();
		overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
	}

	boolean show_pwd_flag = false;// 默认隐藏
	boolean show_again_pwd_flag = false;// 默认隐藏

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.image_pwd_show:
			// 显示密码
			show_pwd_flag = !show_pwd_flag;
			if (show_pwd_flag) {
				// 显示密码
				edt_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
				image_show_pwd.setImageResource(R.drawable.icon_show);
			} else {
				// 隐藏密码
				edt_pwd.setInputType(InputType.TYPE_CLASS_TEXT
						| InputType.TYPE_TEXT_VARIATION_PASSWORD);
				image_show_pwd.setImageResource(R.drawable.icon_hide);
			}
			break;
		case R.id.image_again_pwd_show:
			// 显示密码
			show_again_pwd_flag = !show_again_pwd_flag;
			if (show_again_pwd_flag) {
				// 显示密码
				edt_pwd_two
						.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
				image_show_two_pwd.setImageResource(R.drawable.icon_show);
			} else {
				// 隐藏密码
				edt_pwd_two.setInputType(InputType.TYPE_CLASS_TEXT
						| InputType.TYPE_TEXT_VARIATION_PASSWORD);
				image_show_two_pwd.setImageResource(R.drawable.icon_hide);
			}
			break;
		case R.id.image_pwd_delete:
			edt_pwd.setText("");
			break;
		case R.id.image_again_pwd_delete:
			edt_pwd_two.setText("");
			break;
		case R.id.line_get_code:
			// 获取验证码
			getCode();
			break;

		case R.id.bt_next:
			next();
			break;
		case R.id.bt_sure:
			// sure
			sure();
			break;
		default:
			break;
		}
	}

	/**
	 * 获取验证码
	 */
	void getCode() {
		if (!Util.hasNetwork(ChangePasswordActivity.this)) {
			showTextOne(getString(R.string.no_network).toString(), false);
			return;
		}
		line_get_code.setEnabled(false);
		num = 60;
		handler.post(runnable);

		final MyProgressDialog progressDialog = new MyProgressDialog(
				ChangePasswordActivity.this);
		progressDialog.setContent(getString(R.string.getting).toString());
		progressDialog.show();
		ComyouHttpProgram httpProgram = new ComyouHttpProgram();
		httpProgram.add("targetPhoneNum", phoneNum);
		httpProgram.add("type", 2 + "");
		ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
				+ "getauthcode.php");
		httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

			@Override
			public void onResponse(String reString) {
				progressDialog.dismiss();
				Log.e("tag", reString);
				try {
					JSONObject jsonObject = new JSONObject(reString);
					int status = jsonObject.getInt("err");
					if (status == 0) {
						handler.sendEmptyMessage(1);

					} else {
						num = -1;
						handler.sendEmptyMessage(2);
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(String arg0, IOException arg1) {
				progressDialog.dismiss();
				num = -1;
				handler.sendEmptyMessage(2);
			}

		});
	}

	/**
	 * next
	 */
	String phoneNum = "", code = "";

	void next() {
		if (!Util.hasNetwork(ChangePasswordActivity.this)) {
			showTextOne(getString(R.string.no_network).toString(), false);
			return;
		}

		if (TextUtils.isEmpty(edt_code.getText())
				|| edt_code.getText().toString().length() < 6) {

			showTextOne(getString(R.string.import_auth).toString(), false);
			return;
		}
		phoneNum = mySharedPreferences.getPhoneNum();
		code = edt_code.getText().toString();

		line_one.setVisibility(View.GONE);
		line_two.setVisibility(View.VISIBLE);
		xml_choice = 2;
	}

	/**
	 * set pwd
	 */
	void sure() {
		if (!Util.hasNetwork(ChangePasswordActivity.this)) {
			showTextTwo(getString(R.string.no_network).toString(), false);
			return;
		}
		if (TextUtils.isEmpty(edt_pwd.getText())) {

			showTextTwo(getString(R.string.pwd_hint).toString(), false);
			return;
		}
		if (TextUtils.isEmpty(edt_pwd_two.getText())) {
			showTextTwo(getString(R.string.pwd_hint).toString(), false);
			return;
		}

		String pwd_one = edt_pwd.getText().toString();
		String pwd_two = edt_pwd_two.getText().toString();
		if (pwd_one.length() < 6 || pwd_two.length() < 6) {
			showTextTwo(getString(R.string.pwd_short).toString(), false);
			return;
		}
		if (pwd_one.length() > 20 || pwd_two.length() > 20) {
			showTextTwo(getString(R.string.pwd_more).toString(), false);
			return;
		}

		if (!pwd_one.equals(pwd_two)) {
			showTextTwo(getString(R.string.pwd_un_same).toString(), false);
			return;
		}

		Log.e("tag", "code:"+code+" pwd:"+pwd_one);
		final MyProgressDialog progressDialog = new MyProgressDialog(
				ChangePasswordActivity.this);
		progressDialog.setContent(getString(R.string.getting).toString());
		progressDialog.show();
		ComyouHttpProgram httpProgram = new ComyouHttpProgram();
		httpProgram.add("phoneNum", phoneNum);
		httpProgram.add("pwd", MD5Util.md5(pwd_one));
		httpProgram.add("authcode", code);
		ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
				+ "changepwd.php");
		httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

			@Override
			public void onResponse(String reString) {
				progressDialog.dismiss();
				Log.e("tag", reString);
				try {
					JSONObject jsonObject = new JSONObject(reString);
					int status = jsonObject.getInt("err");
					if (status == 0) {
						handler.sendEmptyMessage(3);

					} else {
						// 0 成功 1：缺少参数 2：手机号码已被注册 3：验证码不正确 4：验证码过期
						num = -1;
						Message msg = new Message();
						msg.what = 4;
						switch (status) {
						case 2:
							msg.obj = getText(R.string.phone_no_has).toString();
							break;
						case 3:
							msg.obj = getText(R.string.code_wrong).toString();
							break;
						case 4:
							msg.obj = getText(R.string.code_data_more)
									.toString();
							break;

						default:
							msg.obj = getText(R.string.regist_fail).toString();
							break;
						}

						handler.sendMessage(msg);
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(String arg0, IOException arg1) {
				progressDialog.dismiss();
				num = -1;

			}
		});
	}

	/**
	 * 自定义提示
	 * 
	 * @param str
	 */
	Toast toast = null;

	void showToast(String str) {
		if (toast != null) {
			toast.cancel();
		}
		LayoutInflater inflater = getLayoutInflater();
		View view = inflater.inflate(R.layout.toastshow, null);
		TextView textView = (TextView) view.findViewById(R.id.toastshow);
		textView.setText(str);
		toast = new Toast(this);
		double d = getResources().getDisplayMetrics().density;
		toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(view);
		toast.show();
	}

	void showTextOne(String str, boolean erroy) {
		tv_one_result.setText(str);
		if (erroy) {
			tv_one_result.setTextColor(getResources().getColor(
					R.color.item_white));
		} else {
			tv_one_result.setTextColor(getResources().getColor(
					R.color.item_orange));
		}
	}

	void showTextTwo(String str, boolean erroy) {
		tv_two_result.setText(str);
		if (erroy) {
			tv_two_result.setTextColor(getResources().getColor(
					R.color.item_white));
		} else {
			tv_two_result.setTextColor(getResources().getColor(
					R.color.item_orange));
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				// 获取验证码成功

				String str = String.format(getString(R.string.code_success)
						.toString(), phoneNum);

				showTextOne(str, true);

				break;
			case 2:
				// 获取验证码失败

				showTextOne(getString(R.string.code_fail).toString(), true);
				break;
			case 3:
				// 密码修改成功
				showToast(getString(R.string.pwd_update_success).toString());
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						ChangePasswordActivity.this.finish();
						overridePendingTransition(R.anim.enter_left,
								R.anim.exit_right);
					}
				}, 1000);
				break;
			case 4:
				// 密码修改失败
				String str_fail = (String) msg.obj;
				showTextTwo(str_fail, false);
				break;

			default:
				break;
			}
		};
	};

	/**
	 * 60s倒计时
	 */
	int num = 60;
	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub

			if (num >= 0) {

				tv_get_code.setText(num + "s");

				num--;
				handler.postDelayed(this, 1000);
			} else {
				num = 60;
				line_get_code.setEnabled(true);
				tv_get_code.setText(getString(R.string.reset_code).toString());
			}

		}
	};
	/**
	 * 显示或隐藏删除图片
	 * 
	 * @param str
	 */

	Runnable clearRunnable = new Runnable() {

		@Override
		public void run() {
			if (xml_choice == 1) {

				if (!TextUtils.isEmpty(edt_code.getText())) {
					btn_next.setEnabled(true);
					btn_next.setTextColor(getResources().getColor(
							R.color.item_white));
					btn_next.setBackgroundResource(R.drawable.bg_round_stroke_white_5dp);
				} else {
					btn_next.setEnabled(false);
					btn_next.setTextColor(getResources().getColor(
							R.color.item_gray));
					btn_next.setBackgroundResource(R.drawable.bg_round_stroke_gray_5dp);
				}

			} else {
				if (TextUtils.isEmpty(edt_pwd.getText())) {
					image_clear_pwd.setVisibility(View.INVISIBLE);
				} else {
					image_clear_pwd.setVisibility(View.VISIBLE);
				}
				if (TextUtils.isEmpty(edt_pwd_two.getText())) {
					image_clear_two_pwd.setVisibility(View.INVISIBLE);
				} else {
					image_clear_two_pwd.setVisibility(View.VISIBLE);
				}
				if (edt_pwd.getText().toString().length() >= 6
						&& edt_pwd_two.getText().toString().length() >= 6) {
					btn_sure.setEnabled(true);
					btn_sure.setTextColor(getResources().getColor(
							R.color.item_white));
					btn_sure.setBackgroundResource(R.drawable.bg_round_stroke_white_5dp);
				} else {
					btn_sure.setEnabled(false);
					btn_sure.setTextColor(getResources().getColor(
							R.color.item_gray));
					btn_sure.setBackgroundResource(R.drawable.bg_round_stroke_gray_5dp);
				}

			}
			handler.postDelayed(clearRunnable, 500);
		}
	};

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();

		overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
	}

	void showSucessDialog(String str) {
		final MyDialog myDialog = new MyDialog(ChangePasswordActivity.this);
		myDialog.setContent(str);
		myDialog.getLeftButton().setText(getText(R.string.ok));
		myDialog.getLeftButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ChangePasswordActivity.this.finish();
				overridePendingTransition(R.anim.enter_left, R.anim.exit_right);

			}
		});
	}
}
